<template>
  <el-dialog
    v-model="dialogVisible"
    :destroy-on-close="true"
    :align-center="true"
    width="50%"
    :title="`${dialogData.title}考证信息`"
  >
    <el-form
      ref="jobFormRef"
      :rules="rules"
      :disabled="dialogData.isView"
      :model="dialogData.itemInfo"
      label-width="180px"
      label-suffix=" :"
    >
      <!-- <div class="info-title">培训考证信息</div> -->
      <el-form-item label="公司">
        <el-select size="large" style="width: 100%" v-model="dialogData.itemInfo.jobCompanyId" placeholder="请选择公司">
          <el-option v-for="item in jobCompanys" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="考证类型">
        <el-tree-select
          filterable
          multiple
          multiple-limit="10"
          v-model="dialogData.itemInfo.trainIds"
          :data="dialogData.jobTypes"
          :render-after-expand="false"
          placeholder="请选择考证类型"
          style="width: 100%"
        ></el-tree-select>
      </el-form-item>
      <el-form-item label="标题" prop="title">
        <el-input size="large" placeholder="请输入标题" v-model="dialogData.itemInfo.title" maxlength="22" show-word-limit />
      </el-form-item>
      <el-form-item label="内容" prop="content">
        <WangEditor height="200px" v-model:value="dialogData.itemInfo.content" />
      </el-form-item>
      <el-form-item label="地址">
        <div class="address-wrapper">
          <div class="address-input">
            <el-input
              readonly
              placeholder="请选择详细地址"
              v-model="dialogData.itemInfo.jobAddress.address"
              size="large"
              maxlength="80"
              show-word-limit
            >
            </el-input>
          </div>
          <div class="address-btn">
            <el-button :icon="Location" size="large" type="primary" style="width: 100%" @click="handleOpenDialog">
              请选择地址
            </el-button>
          </div>
        </div>
      </el-form-item>
      <el-form-item label="联系人">
        <el-input
          placeholder="请填写联系人"
          v-model="dialogData.itemInfo.contactor"
          size="large"
          maxlength="15"
          show-word-limit
        />
      </el-form-item>
      <el-form-item>
        <el-radio-group v-model="dialogData.itemInfo.contactGender">
          <el-radio v-for="item in genderType" :label="item.value" :key="item.value">
            {{ item.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="联系电话">
        <el-input
          placeholder="请填写联系人电话"
          v-model="dialogData.itemInfo.contactPhone"
          size="large"
          maxlength="15"
          show-word-limit
        />
      </el-form-item>
      <el-form-item label="培训图片">
        <UploadImgs
          v-model:fileList="dialogData.fileList"
          :disabled="dialogData.isView"
          :file-size="2"
          width="140px"
          height="140px"
          :api="uploadTrainImg"
        >
          <template #tip> 不超过 2M, 最多5个 </template>
        </UploadImgs>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button v-show="!dialogData.isView" @click="handleJobOffline">下架</el-button>
      <el-input
        v-model="refuseContent"
        v-show="dialogData.isView"
        placeholder="请填写拒绝原因"
        :prefix-icon="EditPen"
        style="width: 260px; margin-left: 10px"
      />
      <el-button size="large" type="danger" @click="handleAduitFail" v-show="dialogData.isView">拒绝</el-button>
      <el-button size="large" type="success" @click="handleAduitPass" v-show="dialogData.isView">通过</el-button>
      <el-button size="large" type="primary" @click="handleLoadNext" v-show="dialogData.isView">审核下一个</el-button>
      <el-button @click="dialogVisible = false">关闭</el-button>
      <el-button type="primary" size="large" v-show="!dialogData.isView" @click="handleSubmit" :loading="btnLoading">
        确认发布
      </el-button>
      <el-divider />
      <div class="jobstatus-wrapper" v-show="dialogData.isView">
        <el-alert
          :title="`岗位状态 &nbsp;:&nbsp; ${filterEnum(dialogData.itemInfo.status, jobStatusType)}`"
          type="info"
          show-icon
          :closable="false"
        />
      </div>
    </template>
  </el-dialog>
  <mapDialog ref="dialogRef" @refresh-data="handleRefreshMapData"></mapDialog>
</template>
<script lang="ts" setup>
import { getOptTitle, OptEnum } from "@/biz/eenum/appEnum";
import { CommonTree } from "@/biz/interface";
import { DialogParam } from "@/biz/interface/DialogType";
import { TrainEntity } from "@/biz/interface/JobType";
import { ElMessage, FormInstance } from "element-plus";
import { onMounted, reactive, ref } from "vue";
import {
  saveJobApi,
  getJobInfoApi,
  setJobOffline,
  getTrainCompanyVoListApi,
  getTrainTypesTreeApi,
  getNextJobApi
} from "@/api/modules/cpyjob/train";
import { uploadTrainImg } from "@/api/modules/upload";
import UploadImgs from "@/components/Upload/ImgMultiple.vue";
import mapDialog, { AddressVo } from "@/components/Map/index.vue";
import { Location, EditPen } from "@element-plus/icons-vue";
import WangEditor from "@/components/WangEditor/index.vue";
import { genderType } from "@/biz/datas/sysData";
import { useHandleData } from "@/hooks/useHandleData";
import { auditFailApi, auditPassApi } from "@/api/modules/sysjob/job";
import { jobStatusType } from "@/biz/datas/appData";
import { filterEnum } from "@/utils";

interface PostDialogOption extends DialogParam {
  //弹出表单的标题
  title: string;
  // 是否是查看状态，查看状态是不可以提交数据
  isView: boolean;
  // 图片
  fileList: [];
  // 岗位类型树
  jobTypes: CommonTree[];
  //当前的数据对象
  itemInfo: TrainEntity;
}

//提交按钮，避免多次提交
const btnLoading = ref(false);
const jobCompanys = ref([] as any);
//弹出框的参数
const dialogVisible = ref(false);
const dialogData = reactive<PostDialogOption>({
  optType: OptEnum.UNKNOW,
  title: "",
  isView: false,
  fileList: [],
  jobTypes: [],
  itemInfo: {
    title: "",
    // * 职位描述
    content: "",
    // * 联系人
    contactor: "",
    // * 联系电话
    contactPhone: "",
    contactGender: 1,
    // 地址信息
    jobAddress: {},
    // *  培训图片
    imgs: [],
    // *  培训类型，多个
    trainIds: []
  }
});

//数据较验
const rules = reactive({
  title: [{ required: true, message: "请填写职位名称", trigger: "blur" }],
  content: [{ required: true, message: "请填写岗位内容", trigger: "blur" }]
});

//页面事件
const emits = defineEmits(["refresh-list"]);

// 提交数据（新增/编辑）
const jobFormRef = ref<FormInstance>();
const handleSubmit = () => {
  btnLoading.value = true;
  jobFormRef.value!.validate(async valid => {
    if (!valid) {
      btnLoading.value = false;
      return;
    }
    try {
      if (dialogData.optType === OptEnum.CREATE || dialogData.optType === OptEnum.EDIT) {
        // console.log(
        //   "dialogData.itemInfo.jobAddress",
        //   dialogData.itemInfo.jobAddress
        // );

        if (!dialogData.itemInfo.jobAddress.areaName) {
          ElMessage.error("请重新选择区域信息");
          return;
        }

        // 市下面的区域是[] ， 没有区域的信息
        if (dialogData.itemInfo.jobAddress.areaName.length == 0) {
          dialogData.itemInfo.jobAddress.areaName = "";
        }
        // 市[] ， 县级市
        if (dialogData.itemInfo.jobAddress.areaName) {
          if (dialogData.itemInfo.jobAddress.cityName.length == 0) {
            dialogData.itemInfo.jobAddress.cityName = "";
          }
        }

        //拼成后台的坐标格式
        dialogData.itemInfo.jobAddress.location = dialogData.itemInfo.jobAddress.lng + "," + dialogData.itemInfo.jobAddress.lat;

        if (dialogData.fileList) {
          dialogData.itemInfo.imgs = [];
          dialogData.fileList.forEach(file => {
            // console.log("每个文件, ", file, file.url);
            if (file && file.url) {
              dialogData.itemInfo.imgs.push(file.url);
            }
          });
        }

        let res = await saveJobApi({ ...dialogData.itemInfo });
        if (res.data) {
          ElMessage.success({ message: `保存成功！` });
          //刷新列表数据
          // eslint-disable-next-line vue/custom-event-name-casing
          emits("refresh-list");
          dialogVisible.value = false;
        }
      }
    } catch (error) {
      console.log("出现异常情况,", error);
    } finally {
      btnLoading.value = false;
    }
  });
};

// 岗位下架
const handleJobOffline = async () => {
  if (dialogData.rowData && dialogData.rowData.id) {
    let res = await setJobOffline({ id: dialogData.rowData.id });
    if (res.data) {
      ElMessage.success({ message: `岗位已下架` });
      //刷新列表数据
      // eslint-disable-next-line vue/custom-event-name-casing
      emits("refresh-list");
      dialogVisible.value = false;
    }
  }
};

// 接收父组件传过来的参数
const acceptParams = (params: DialogParam): void => {
  dialogData.optType = params.optType;
  dialogData.rowData = params.rowData;
  dialogData.isView = dialogData.optType === OptEnum.VIEW;
  dialogData.title = getOptTitle(dialogData.optType);

  if (dialogData.optType === OptEnum.CREATE) {
    initItemInfo();
  } else if (dialogData.rowData && dialogData.rowData.id) {
    getItemInfo(dialogData.rowData.id);
  }

  dialogVisible.value = true;
};

//初始化页面的数据
const initItemInfo = (): void => {
  dialogData.itemInfo = {
    title: "",
    // * 职位描述
    content: "",
    // * 联系人
    contactor: "",
    // * 联系电话
    contactPhone: "",
    contactGender: 1,
    // 地址信息
    jobAddress: {},
    // *  培训图片
    imgs: [],
    // *  培训类型，多个
    trainIds: []
  };
  dialogData.fileList = [];
};

//获取当前数据的详情，直接调用接口获取数据
const getItemInfo = async (id: string) => {
  if (id) {
    let { data } = await getJobInfoApi({ id });
    dialogData.itemInfo = data as unknown as TrainEntity;
    dialogData.itemInfo.jobAddress = dialogData.itemInfo.jobAddress || {
      address: ""
    };
    dialogData.fileList.length = 0;
    let imgIdx = 1;
    if (dialogData.itemInfo.imgs) {
      dialogData.itemInfo.imgs.forEach(img => {
        dialogData.fileList.push({ name: imgIdx, url: img });
        imgIdx = imgIdx + 1;
      });
    }
  }
};

//刷新地图的返回数据
const handleRefreshMapData = (val: AddressVo) => {
  // console.log("返回的地址信息", val);
  //填充地图数据
  dialogData.itemInfo.jobAddress = val;
};

const refuseContent = ref("");
const handleAduitFail = async () => {
  if (dialogData.itemInfo && dialogData.itemInfo.id) {
    await useHandleData(
      auditFailApi,
      { id: dialogData.itemInfo.id!, refuseCtn: refuseContent.value || "" },
      `【${dialogData.itemInfo.title}】岗位，审核不通过`
    );
  }
};

// 审核通过
const handleAduitPass = async () => {
  if (dialogData.itemInfo && dialogData.itemInfo.id) {
    await auditPassApi({
      id: dialogData.itemInfo.id
    }).then(res => {
      if (res.data) {
        ElMessage.success("审核通过");
      }
    });
  }
};

// 加载下一个
const handleLoadNext = () => {
  // getNextJobApi;
  if (dialogData.itemInfo && dialogData.itemInfo.id) {
    getNextItemInfo(dialogData.itemInfo.id);
  }
};

// 获取下一条等待审核的岗位信息
const getNextItemInfo = async (id: string) => {
  if (id) {
    let { data } = await getNextJobApi({ id });
    if (data) {
      dialogData.itemInfo = data as unknown as TrainEntity;
      dialogData.itemInfo.jobAddress = dialogData.itemInfo.jobAddress || {
        address: ""
      };
      dialogData.fileList.length = 0;
      let imgIdx = 1;
      if (dialogData.itemInfo.imgs) {
        dialogData.itemInfo.imgs.forEach(img => {
          dialogData.fileList.push({ name: imgIdx, url: img });
          imgIdx = imgIdx + 1;
        });
      }
    } else {
      ElMessage.success("没有待审核数据了.");
    }
  }
};

// 打开 dialog(新增、查看、编辑)
const dialogRef = ref();
const handleOpenDialog = () => {
  let params = {};
  dialogRef.value.acceptParams(params);
};

onMounted(() => {
  getTrainCompanyVoListApi({}).then(res => {
    jobCompanys.value = res.data;
  });
  getTrainTypesTreeApi({}).then(res => {
    dialogData.jobTypes = res.data as unknown as CommonTree[];
  });
});

//页面参数
defineExpose({
  acceptParams
});
</script>
<style scoped lang="scss">
.address-box {
  display: flex;
}

.file-upload-box {
  display: flex;
  width: 100%;
  // border: 1px solid red;
}

.work-wrapper {
  display: flex;
  flex-direction: column;
  width: 100%;

  .btn-wrapper {
    height: 30px;
    // border: 1px solid red;
  }
  .item-wrapper {
    margin: 5px 0;
    // border: 1px solid green;

    .item-mid {
      margin: 0 5px;
    }
  }
}

.address-wrapper {
  width: 100%;
  // border: 1px solid red;
  display: flex;
  align-items: center;

  .address-input {
    flex: 1;
  }

  .address-btn {
    width: 20%;
  }
}
</style>
